 <template>
  <div class="container">
    <div class="main">
      <div class="main_content">
        <div class="main_header">
          <a-steps :current="currentIndex">
            <a-step>
              <!-- <span slot="title">Finished</span> -->
              <template slot="title"> 组卷配置 </template>
              <span slot="description">作为生成组卷的必要部分</span>
            </a-step>
            <a-step
              title="选题信息"
              description="在表格中选中合适的问题,进行组卷"
            />
          </a-steps>
        </div>
        <div class="main_table">
          <!-- data-source 数据源,column 列名  row-selection列表项是否可选择	-->
          <!-- rowSelection 是计算属性进行加工处理 -->
          <a-form-model
            ref="ruleForm"
            :model="form"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-tabs
              :activeKey="activeKey"
              default-active-key="1"
              :tab-position="mode"
              :style="{ height: '800px' }"
              @change="change"
            >
              <a-tab-pane tab="组卷配置" key="1">
                <!-- 试卷名称  -->
                <a-form-model-item ref="test" label="试卷名称" prop="test">
                  <a-input
                    v-model="form.test"
                    @blur="
                      () => {
                        $refs.test.onFieldBlur();
                      }
                    "
                  />
                </a-form-model-item>

                <a-form-model-item ref="desc" label="组卷描述" prop="desc">
                  <a-input
                    v-model="form.desc"
                    @blur="
                      () => {
                        $refs.desc.onFieldBlur();
                      }
                    "
                  />
                </a-form-model-item>
                <!-- prop 校验对应名字 -->
                <a-form-model-item label="组卷类型">
                  <a-radio-group v-model="form.type" @change="changeSelect">
                    <a-radio value="1"> 考试 </a-radio>
                    <a-radio value="2"> 练习</a-radio>
                  </a-radio-group>
                </a-form-model-item>
                <a-form-model-item label="组卷性质">
                  <a-radio-group
                    v-model="is_limit_time"
                    @change="changeSelect2"
                  >
                    <a-radio value="1" :checked="focus_limit_time"
                      >永久</a-radio
                    >
                    <a-radio value="0" :checked="focus_not_limit_time"
                      >限时</a-radio
                    >
                  </a-radio-group>
                </a-form-model-item>
                <!-- 当不选中第三个选项的时候 显示 否则不显示 -->
                <a-form-model
                  v-if="is_limit_time != 1"
                  ref="ruleForm2"
                  :rules="rules"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol"
                >
                  <a-form-item
                    label="开始/结束日期"
                    style="margin-bottom: 0"
                    v-if="showClassVisible == false"
                  >
                    <div>
                      <a-range-picker
                        @change="getDateTime"
                        showToday
                        :default-value="[
                          moment(getCurrentDataL(), dateFormat),
                          moment(getCurrentDataR(), dateFormat),
                        ]"
                        :format="dateFormat"
                      >
                        <template slot="dateRender" slot-scope="current">
                          <div
                            class="ant-calendar-date"
                            :style="getCurrentStyle(current)"
                          >
                            {{ current.date() }}
                          </div>
                        </template>
                      </a-range-picker>
                    </div>
                  </a-form-item>
                  <a-form-item
                    label="开始/结束日期"
                    style="margin-bottom: 0"
                    v-else
                  >
                    <div>
                      <a-range-picker @change="getDateTime">
                        <template slot="dateRender" slot-scope="current">
                          <div
                            class="ant-calendar-date"
                            :style="getCurrentStyle(current)"
                          >
                            {{ current.date() }}
                          </div>
                        </template>
                      </a-range-picker>
                    </div>
                  </a-form-item>
                  <a-form-item label="开始/结束时间" style="margin-bottom: 0">
                    <a-time-picker
                      v-model="handleTime.startTime"
                      format="HH:mm:ss"
                      @change="getStartTime"
                      :open="open"
                      @openChange="handleOpenChange"
                      style="margin-right: 10px"
                    >
                    </a-time-picker>
                    -
                    <a-time-picker
                      :open.sync="open2"
                      style="margin-left: 10px"
                      @change="getEndTime"
                      v-model="handleTime.endTime"
                    >
                    </a-time-picker>
                  </a-form-item>
                </a-form-model>
                <a-form-model
                  v-else
                  ref="ruleForm2"
                  :rules="rules"
                  :label-col="labelCol"
                  :wrapper-col="wrapperCol"
                >
                  <a-form-item label="开始时间">
                    <div>
                      <a-date-picker
                        show-time
                        placeholder="请确认开始时间"
                        @change="onDataChange"
                        @ok="confirm"
                        v-model="limit_time"
                      />
                    </div>
                  </a-form-item>
                </a-form-model>
                <a-form-model-item
                  :wrapper-col="{ span: 14, offset: 7 }"
                  style="margin-top: 50px"
                >
                  <a-button type="primary" @click="onSubmit"> 下一页 </a-button>
                  <a-button style="margin-left: 10px" @click="resetForm">
                    重置
                  </a-button>
                </a-form-model-item>
              </a-tab-pane>
              <a-tab-pane tab="选题信息" key="2">
                <div class="table">
                  <select-exam-question-table
                    @getFocusItemInTable="getFocusItemInTable"
                    :totalScore="totalScore"
                    :totalItem="totalItem"
                    :records="record"
                  >
                  </select-exam-question-table>
                </div>
                <a-button
                  type="primary"
                  class="btn_finish_Tab2"
                  @click="addOrUpdateExam"
                  size="large"
                >
                  {{ desWord }}
                </a-button>
              </a-tab-pane>
              <!-- 新增就出现选择班级的 指定 修改就不出现 -->
            </a-tabs>
          </a-form-model>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import selectExamQuestionTable from "../components/exam-select-question-table.vue";
import selectExamClassTable from "./examAssignClass.vue";
import moment from "moment";
export default {
  data() {
    return {
      test: 0,
      //

      havechooseIds: [],
      totalMessage: [],
      // prop 返回给子组件
      totalItem: 0,
      totalScore: 0,
      limit_time: "",
      focus_not_limit_time: false,
      focus_limit_time: false,
      is_limit_time: "",
      dateFormat: "YYYY-MM-DD",
      // 控制班级框的显示与隐藏
      showClassVisible: true,
      // Tab2 中选中的id 和所有数据
      idList: [],
      selectForm: [],
      is_modify: false,
      // 时间模块
      open: false,
      open2: false,
      // 默认配置信息
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        //   该试卷的描述信息
        desc: "",
        class_id: "",
        class: [],
        // 试卷名称
        test: "",
        // //试卷那类型;
        type: "0",
        startTime: "",
        endTime: "",
        // 试卷题
        questionIdMap: "",
        // 分配的学生信息
        studentId: [],
      },
      rules: {
        desc: [
          {
            required: true,
            message: "请填写试卷的描述信息",
            trigger: "blur",
          },
        ],
        test: [
          {
            required: true,
            message: "请填写试卷的名称",
            trigger: "blur",
          },
        ],
        // answer
        answer: [
          {
            required: true,
            message: "请填写答案",
            trigger: "blur",
          },
        ],

        desc: [
          {
            required: true,
            message: "请填写关于该组卷的描述",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请填写组卷类别",
            trigger: "blur",
          },
        ],
      },
      options: [],
      // 是否能够进入下一页
      allowToNextTab: false,
      // 当前进度条的索引
      currentIndex: 0,
      //Tab Key
      activeKey: "1",
      mode: "left",

      record: {},
      classStudentList: "",
      handleTime: {
        // 用户选择的开始时间 --(时分秒)
        startTime: "",
        endTime: "",
        // 稍加转换的时分秒
        startTimeToChange: "",
        endTimeToChange: "",
        // 日期
        startTimeYear: "",
        endTimeYear: "",
      },
    };
  },
  components: {
    selectExamQuestionTable,
    selectExamClassTable,
  },
  created() {
    this.init();
  },
  methods: {
    // onChange
    onDataChange(value, dateString) {
      // mom
      // console.log("Formatted Selected Time: ", dateString);
      let formatDate = new Date(dateString);
      this.form.startTime = formatDate.getTime();
      this.form.endTime = "";
      // console.log(" startTime: ", this.form.startTime);
    },
    confirm(value) {
      // moments
      // console.log("confirm: ", value);
    },
    // 完成分配 组卷完成
    async addOrUpdateExam() {
      let questionMap = {};
      // console.log("sss", this.selectForm);
      //  1.先把questionMap 整合出来
      this.idList.forEach((item) => {
        // 在idList 取一项 比较所有的 如果items 大于的话 就.
        this.selectForm.forEach((items) => {
          // idList中选中的id
          if (item == items.id) {
            // 动态的key指
            questionMap[item] = Number(items.score);
          }
        });
      });
      if (!this.record) {
        this.form.studentId = [...this.classStudentList];
        // 去重 班级的学生 和 选择的学生
        this.form.studentId = this.unique(this.form.studentId);
        const { data: res } = await this.$http.post("/admin/exam", {
          students: this.form.studentId,
          title: this.form.test,
          desc: this.form.desc,
          type: this.form.type,
          startTime: this.form.startTime,
          endTime: this.form.endTime,
          questions: questionMap,
        });
        if (res.code == 200) {
          this.common.notify("success", "新增成功");
          this.$router.push({
            name: "exams",
          });
        } else {
          this.common.notify("error", "新增失败");
        }
      } else {
        //修改操作
        // 如果 form.type 为空 说明选择了 永久练习 则给formType 赋予初值
        const { data: res } = await this.$http.put("/admin/exam", {
          id: this.record.id,
          title: this.form.test,
          desc: this.form.desc,
          type: this.form.type,
          startTime: this.form.startTime,
          endTime: this.form.endTime,
          questions: questionMap,
        });
        if (res.code == 200) {
          this.common.notify("success", "修改成功");
          this.$router.push({
            name: "exams",
          });
        } else {
          this.common.notify("error", "修改失败");
        }
      }
    },
    // Tab4 emit 方法用于学生参数
    getStudentDate(studentIdList) {
      this.form.studentId = studentIdList;
    },

    moment,
    startTime() {
      if (this.showClassVisible == true) {
        return null;
      } else {
        let arr = this.record.startTime.split(" ");
        this.handleTime.startTime = arr[1]; //设置默认值 为之前新增时确定的
        return arr[1];
      }
    },
    endTime() {
      if (this.showClassVisible == true) {
        return null;
      } else {
        let arr = this.record.endTime.split(" ");
        this.handleTime.endTime = arr[1]; //设置默认值 为之前新增时确定的
        return arr[1];
      }
    },
    // 日期部分左边设定初值
    getCurrentDataL() {
      if (this.showClassVisible == true || this.record.endTime == null) {
        return null;
      } else {
        let arr = this.record.startTime.split(" ");
        this.handleTime.startTimeYear = arr[0];
        return arr[0];
      }
    },
    // 日期部分右边设置初始值
    getCurrentDataR() {
      if (this.showClassVisible == true || this.record.endTime == null) {
        return null;
      } else {
        let arr = this.record.endTime.split(" ");
        this.handleTime.endTimeYear = arr[0];
        return arr[0];
      }
    },
    // 用于拿到 表格中 用户选中的内容
    // 列表中的数据
    getFocusItemInTable(idList, data) {
      // console.log("data", data);
      // console.log("getFocusItemInTable", idList);
      // 1.  回显的时候 选择第一个 之后点击翻页的时候 也会法来请求
      this.selectForm = data;
      console.log("111", this.havechooseIds);
      //第一次为空 就先拿过来
      this.idList = this.unique(idList);
      this.totalItem = this.idList.length;
      this.totalScore = 0;
      // 判断一个id 是否已经被加过分了
      let idSign = [];

      data.forEach((item) => {
        this.idList.forEach((key) => {
          // 一次只会加一道题 而我是遍历整个forEach
          if (item.id == key && !idSign.includes(item.id)) {
            // console.log("id", item.id);
            idSign.push(item.id);
            this.totalScore = this.totalScore + Number(item.score);
          }
        });
      });

      for (let key in this.havechooseIds) {
        let flag = false;
        data.forEach((item) => {
          // 如果已经选择的内容 并不在当前页中
          if (key == item.id) {
            flag = true;
          }
        });
        if (flag == false) {
          this.totalScore = this.totalScore + Number(this.havechooseIds[key]);
        }
      }
      // 增加一个操作 本页9个 第二页1个 那么我加一个 应该是11个 而不是10个。
    },
    // 对于时间的加工处理
    // 将开始时间转化为毫秒数
    getStartTime(value) {
      // 提取空间中 我们想要的 时间类型
      let d = new Date(this.handleTime.startTime);
      let date = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
      // 转化为时间戳
      let formatDate = new Date(this.handleTime.startTimeYear + " " + date);

      this.form.startTime = formatDate.getTime();
    },
    // 将结束时间转化为毫秒数
    getEndTime(value) {
      let d = new Date(this.handleTime.endTime);
      let date = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
      // 转化为时间戳
      let formatDate = new Date(this.handleTime.endTimeYear + " " + date);
      this.form.endTime = formatDate.getTime();
    },
    getDateTime(data) {
      if (data) {
        this.handleTime.startTimeYear = data[0].format("YYYY-MM-DD");
        this.handleTime.endTimeYear = data[1].format("YYYY-MM-DD");
        this.getStartTime();
        this.getEndTime();
      }
      if (this.form.startTime) {
        // 如果已经存在 说明是时间的设定不对 修改日期的时候 重新获取毫秒数
      }
    },
    // 日期部分 样式的初始化
    getCurrentStyle(current, today) {
      const style = {};
      if (current.date() === 1) {
        style.border = "1px solid #1890ff";
        style.borderRadius = "50%";
      }

      return style;
    },
    // 时间部分 初始化
    handleOpenChange(open) {
      this.open = open;
    },
    // 时间部分的初始化
    handleClose() {
      this.open = false;
      this.open2 = false;
    },

    async init() {
      // 获取下拉框中的 题库分类选项
      let { record } = this.$route.params;
      // 若 record 则是更新操作
      this.record = record;

      if (record) {
        // console.log("111", record);
        this.totalItem = record.totalNum;

        this.is_modify = true;
        this.showClassVisible = false;
        //
        this.focus_not_limit_time = true;
        this.focus_limit_time = false;
        //
        const { data: res } = await this.$http.get(`/admin/exam/${record.id}`);
        //  解构赋值 分离出 res.data 给data变量
        let { data } = res;
        // console.log("data", data);
        this.record = data;
        this.form.desc = data.desc;
        this.form.test = data.title;
        this.form.class_id = data.id;
        this.havechooseIds = data.questions;
        if (data.endTime) {
          // 如果有值 就进行... 如果没有值 => 永久试卷 => null
          this.is_limit_time = "0";
          if (data.type == "试卷") {
            this.form.type = "1";
          } else {
            this.form.type = "2";
          }
          let arr = this.record.startTime.split(" ");
          let handledata = arr[1];
          this.handleTime.startTime = moment(handledata, "HH:mm:ss");

          let arr2 = this.record.endTime.split(" ");
          handledata = arr2[1];
          this.handleTime.endTime = moment(handledata, "HH:mm:ss");
          this.getStartTime();
          this.getEndTime();
        } else {
          if (data.type == "试卷") {
            this.form.type = "1";
          } else {
            this.form.type = "2";
          }
          this.is_limit_time = "1";
          this.focus_not_limit_time = false;
          this.focus_limit_time = true;
          // 2. 日期的设置
          this.limit_time = data.startTime;
          this.showClassVisible = true;
          this.onDataChange(null, this.limit_time);
        }
      } else {
        this.is_modify = false;
        this.showClassVisible = true;
      }
    },
    // 当 前两个选项选中的时候 默认取消第三个选项的选中
    changeSelect() {
      // this.is_limit_time = "";
    },
    // 当选择 第三个选项的时候 默认取消 前两个的选中
    changeSelect2() {
      // this.form.type = "";
    },
    // 第二页 --> 第三页
    finishExam() {
      // 修改的话 就两项 要转到
      if (this.is_modify) {
        //直接添加
        this.addOrUpdateExam();
      } else {
        // 如果是新增 还有添加班级的选项 就跳转到第三个位置
        this.change("3");
      }
    },
    //第三页 --> 第四页
    finishSelectClass() {
      this.change("4");
    },
    // 从第一个 Tab  跳转到 第二个Tab
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.allowToNextTab = true; //允许到下一页
          this.change("2");
        } else {
          this.openNotificationWithIcon("info");
          return false;
        }
      });
    },
    resetForm() {
      // 清空两个表单
      this.$refs.ruleForm.resetFields();
      this.$refs.ruleForm2.resetFields();
    },
    //   tab栏回调
    change(val) {
      // 不点击 下一页 直接点击 跳转
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.allowToNextTab = true;
        }
      });
      if (this.activeKey < val && this.activeKey == val - 1) {
        // 如果是依次跳转 就判断校验
        //往后跳转要进行验证
        if (this.allowToNextTab) {
          //如果填写项 通过的了验证 就跳转
          // 返回下一个列表 索引对应
          this.currentIndex = Number(val) - 1;
          this.activeKey = val; //active 控制跳转 若表单不完整 不显示跳转
          this.allowToNextTab = false; //重置
        } else {
          //   如果参数没填写全 就想着跳转
          this.openNotificationWithIcon("info");
        }
      } else if (this.activeKey < val && this.activeKey != val - 1) {
        this.common.notify("warning", "请依次确认信息");
      } else {
        //如果往前跳 就不考虑
        if (this.allowToNextTab) {
          //如果填写项 通过的了验证 就跳转
          // 返回下一个列表 索引对应
          this.currentIndex = Number(val) - 1;
          this.activeKey = val; //active 控制跳转 若表单不完整 不显示跳转
          this.allowToNextTab = false; //重置
        }
      }
    },
    // 消息提醒模态
    openNotificationWithIcon(type) {
      if (type == "info") {
        this.$notification[type]({
          message: "存在未知错误",
          description: "可能是由于填写信息没有通过校验所导致,请重新核查",
        });
      } else if (type == "success") {
        this.$notification[type]({
          message: "操作成功",
        });
      }
    },
    // 去重
    unique(array) {
      //一个新的数组
      var arrs = [];
      //遍历当前数组
      for (var i = 0; i < array.length; i++) {
        //如果临时数组里没有当前数组的当前值，则把当前值push到新数组里面
        if (arrs.indexOf(array[i]) == -1) {
          arrs.push(array[i]);
        }
      }
      return arrs;
    },
  },
  computed: {
    // 变量意义在于 2->4 是不行的 要将4 改成 3
    changeKey() {
      // 如果是新增的话 key 为4
      if (this.is_modify == false) {
        return "4";
      } else {
        return "3";
      }
    },
    desWord() {
      return "完成";
    },
  },
};
</script>
<style  lang='less' scoped>
.container {
  box-sizing: border-box;
  display: flex;
  background-color: #eef1f2;
  padding: 35px 75px;
  .main {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-items: center;
    background-color: #eef1f2;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    .main_content {
      padding: 20px;
      padding-top: 20px;
      width: 100%;
      height: 100%;
      background-color: #fff;
      border-radius: 10px;
      .main_header {
        display: flex;
        margin-bottom: 25px;
        .main_table {
          margin-top: 50px;
        }
      }
    }
  }
}
/deep/ .ant-table-thead > tr > th,
.ant-table-tbody > tr > td {
  text-align: center;
}
/deep/ .ant-table-tbody > tr > td {
  // 1516
  text-align: center !important;
}
.disableColor {
  color: #eee;
}
li {
  list-style: none;
  margin-top: 10px;
}
.btn_finish {
  margin-top: 60px;
  margin-left: 480px;
}
.btn_finish_Tab2 {
  margin-top: 220px;
  margin-left: 480px;
}
.table {
  width: 100%;
  height: 500px;
}
.finshScoreTable {
  width: 100%;
  height: 500px;
}
// timepicker 文字居中
/deep/ .ant-time-picker-panel-inner {
  text-align: center !important;
}
/deep/ .ant-time-picker-panel-addon {
  text-align: center !important;
}
</style>